package com.bestcem.xm.award.lua;

import cn.hutool.core.io.FileUtil;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.util.ResourceUtils;

import java.io.File;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author zhenz
 * @description lua 基类
 * @date 2020/6/16 11:15
 */
@Slf4j
@Data
public abstract class BaseLua {

    private RedisScript<Long> redisScript;

    private Lock lock = new ReentrantLock();

    /**
     * 获取lua脚本路径
     *
     * @return
     */
    abstract String getLuaPath();

    /**
     * 获取lua脚本
     *
     * @return
     */
    public RedisScript<Long> getRedisScript() {
        if (redisScript == null) {
            lock.lock();
            try {
                if (redisScript != null) {
                    return redisScript;
                }
                File file = ResourceUtils.getFile(getLuaPath());
                redisScript = new DefaultRedisScript<>(FileUtil.readString(file, StandardCharsets.UTF_8), Long.class);
            } catch (Exception e) {
                log.error("getRedisScript error", e);
            } finally {
                lock.unlock();
            }
        }
        return redisScript;
    }
}
